# !/usr/bin/env python
# -*- coding: utf-8 -*-
"""
 -------------------------------------------------
    File Name:     tree.py
    Description:   
 -------------------------------------------------
 """
import logging
import os
import subprocess

import pyperclip  # 引入 pyperclip 库来操作剪切板

from apitesting.core.base import BaseCommand

# Configure logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)


class Command(BaseCommand):
    def add_arguments(self, parser):
        parser.add_argument(
            "args",  # 固定写法，让基类指定拿这里的值
            metavar="tree",
            nargs="*",
            help="Label for the tree"
        )
        parser.add_argument(
            "-f", "--dir",
            default=".",
            help="指定要生成树状结构的目标目录（默认是当前目录）",
        )
        parser.add_argument(
            "--exclude",
            nargs="*",
            default=[],
            help="指定需要忽略的文件或目录（支持多个）",
        )
        parser.add_argument(
            "--exclude-file",
            default="./scripts/.ignore_tree",
            help="从配置文件中读取需要忽略的文件或目录（每行一个规则）",
        )
        parser.add_argument(
            "-d", "--only-dirs",
            action="store_true",
            help="是否只显示文件夹（默认显示文件和文件夹）",
        )
        parser.add_argument(
            "-o",
            action="store_true",
            help="将结果输出到指定文件。如果不指定，会直接在终端打印",
        )
        parser.add_argument(
            "--copy-to-clipboard",
            action="store_true",
            help="将命令输出结果复制到剪切板",
        )

    def execute(self, *tree_label, **options):
        logger.info(f"label: {tree_label}, options: {options}")
        # logger.info(f"label: {tree_label}, dir: {options}")
        if len(tree_label) > 0:
            target_dir = tree_label[0] or options["dir"]
        else:
            target_dir = options["dir"]
        exclude_patterns = options["exclude"]
        only_dirs = options["only_dirs"]
        copy_to_clipboard = options.get("copy_to_clipboard", False)

        # 检查目录是否存在
        if not os.path.exists(target_dir):
            logger.error(f"Error: Directory '{target_dir}' does not exist.")
            return

        # 检查 tree 命令是否可用
        if os.system("tree --version") != 0:
            print("Error: 'tree' command is not available. Please install it first.")
            return

        # 从配置文件中读取忽略规则
        exclude_file = options.get("exclude_file")
        if exclude_file and os.path.exists(exclude_file):
            with open(exclude_file, "r") as file:
                file_exclude_patterns = [line.strip() for line in file if line.strip()]
                exclude_patterns.extend(file_exclude_patterns)
        # 合并忽略规则
        if exclude_patterns:
            exclude_regex = "|".join(exclude_patterns)  # 使用正则表达式分隔符 |
        else:
            exclude_regex = None

        # 构造 tree 命令
        tree_command = f"tree {target_dir}"  # 指定执行的目录
        if only_dirs:
            tree_command += " -d"  # 添加只显示目录的选项
        if exclude_regex:
            tree_command += f" -I '{exclude_regex}'"

        print(f"Running command: {tree_command}")
        # os.system(tree_command)

        # 使用 subprocess 来捕获命令输出
        try:
            result = subprocess.check_output(tree_command, shell=True, text=True)
            if copy_to_clipboard:
                # 将输出结果复制到剪切板
                pyperclip.copy(result)

            if options.get("o", False):
                # 如果设置了 --output 参数，可以选择将结果保存到文件
                with open('tree_output.txt', 'w') as f:
                    f.write(result)
            else:
                # 否则在终端打印输出
                print(result)
            logger.info("输出已复制到剪贴板.")
        except subprocess.CalledProcessError as e:
            logger.error(f"执行命令时出错: {e}")
            # print(f"Error while executing command: {e}")
